/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_02_03			*/
/*	File:		MrSem.cpp			*/
/********************************************************/

#include "MrSem.h"

CMrSem::CMrSem()
{
	m_iSem = MR_FAILURE;
}

CMrSem::~CMrSem()
{
}

void CMrSem::MrIpcDelete()
{
	if (MR_FAILURE != m_iSem) {
		semctl(m_iSem, IPC_RMID, 0);
	}

	return;
}

int CMrSem::MrIpcCreate(key_t iKey)
{
	MRSEM_U unSem;;

	if (MR_FAILURE != (m_iSem = semget(iKey, 1, IPC_CREAT | IPC_EXCL | 0777))) {
		unSem.m_iValue = 1;
		if (MR_FAILURE == semctl(m_iSem, 0, SETVAL, unSem)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}
	}
	else {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrSem::MrSemAttach(key_t iKey)
{
	if (MR_FAILURE == (m_iSem = semget(iKey, 1, IPC_CREAT | 0777))) {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrSem::MrSemAcquire()
{
	struct sembuf stSem = {0, -1, SEM_UNDO};

	if (MR_FAILURE == semop(m_iSem, &stSem, 1)) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrSem::MrSemRelease()
{
	struct sembuf stSem = {0, 1, SEM_UNDO};

	if (MR_FAILURE == semop(m_iSem, &stSem, 1)) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}
